<template>
  <div class="loginModel">
    <!-- closeLoginModel -->
    <div class="mask" @click="changeIsShowLoginModel(false)"></div>
    <div class="loginBox">
      <img
        class="close"
        src="../assets/img/close.png"
        @click="changeIsShowLoginModel(false)"
      />
      <ul class="loginMethods">
        <li @click="isShowContent = true" :class="{ current: isShowContent }">
          手机号码登录
        </li>
        <!-- 分隔线 -->
        <span></span>
        <li @click="showQrCode" :class="{ current: !isShowContent }">
          微信扫码登录
        </li>
      </ul>
      <div class="loginContent" v-show="isShowContent">
        <div class="cow">
          <input
            type="text"
            placeholder="请输入手机号"
            v-model.trim="phoneNumber"
            ref="phoneInput"
          />
        </div>
        <div class="cow">
          <!-- <input type="text" placeholder="假滑块验证码" /> -->
          <slide-verify
            :l="42"
            :r="18"
            :w="362"
            :h="140"
            :slider-text="msg"
            :imgs="images"
            :style="{ width: '100%' }"
            class="slide-box"
            ref="slideBlock"
            @success="onSuccess"
            @fail="onFail"
            @refresh="onRefresh"
          ></slide-verify>
          <!-- <div>{{ msg }}</div> -->
        </div>
        <div class="cow">
          <input
            type="text"
            placeholder="请输入验证码"
            v-model.trim="messageCode"
          />
          <button class="btn" @click="getCode" v-if="isShowCodeBtn">
            获取验证码
          </button>
          <button class="btn" v-else>{{ count }}</button>
        </div>
        <div class="cow">
          <button class="loginBtn" @click="login">登录</button>
        </div>
      </div>
      <!-- 二维码展示 步骤二：加 id -->
      <div class="qrLogin" id="weixin" v-show="!isShowContent">二维🐎</div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { checkoutPhoneNum } from "@/utils/checkoutPhone/checkoutPhone";
import {
  getCodeApi,
  phoneLoginApi,
  wechatBindingPhoneApi,
  getUserInfoApi,
} from "@/request/api";
export default {
  data() {
    return {
      // 控制登录框显示隐藏的状态数据， Topbar 组件和 Login组件要用到，所以存在 vuex 里，登录方式内容的显示隐藏，只有登录框 Login 用到，所以存在 Login 的 data 里
      isShowContent: true,
      phoneNumber: "",
      msg: "向右滑动",
      images: [
        require("../assets/img/0063ce30b72840e26333476068942c7d.jpeg"),
        require("../assets/img/150 .jpg"),
      ],
      messageCode: "",
      count: 3,
      isShowCodeBtn: true,
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModel: "showModel/changeIsShowLoginModel",
      chanIsLogined: "loginStatus/chanIsLogined",
    }),
    ...mapActions({
      asyncChangeIsShowToast: "showToast/asyncChangeIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    /* closeLoginModel(val) {
      this.changeIsShowLoginModel(val);  // 不用也可以，在标签体里直接写，传false，和后面调用直接 this.changeIsShowLoginModel
    }, */
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    checkout() {
      /**
       * 手机号正则：
       * [0-35-9]  0-3 和 5-9 通过校验，4 不通过校验
       * {n}：表示校验 n 次
       * 16788888888
       */
      if (!checkoutPhoneNum(this.phoneNumber)) {
        // alert("请输入正确的手机号");
        // 调用封装的提示框
        this.asyncChangeIsShowToast({
          isShow: true,
          tMsg: "请输入正确的手机号!",
          tType: "warning",
        });
        this.phoneNumber = "";
        this.$refs.phoneInput.focus();
        return;
      }
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        // alert("请滑动滑块验证码");
        this.asyncChangeIsShowToast({
          isShow: true,
          tMsg: "请滑动滑块验证码!",
          tType: "warning",
        });
        return;
      }
      return true;
    },

    // 发送短信验证码请求
    async getCode() {
      if (!this.checkout()) return;
      // const codeRes = await getCodeApi(this.phoneNumber);
      const codeRes = await getCodeApi({ phone: this.phoneNumber });
      this.isShowCodeBtn = false;
      let timer = null;
      timer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          this.count = 3;
          this.isShowCodeBtn = true;
          clearInterval(timer);
        }
      }, 1000);
      alert("验证码发送成功");
      console.log({ codeRes });
    },

    // 发起手机请求
    async login() {
      // 手机号和滑块验证
      if (!this.checkout()) return;
      // 短信验证码非空校验
      if (!this.messageCode) return alert("短信验证码不能为空");
      // 获取 uuid 用作登录请求方式判断
      const uuid = localStorage.getItem("uuid");
      console.log({ uuid });
      // 把存储响应的变量赋值为空，方便在相反的判断条件里赋值，后面的代码能达到高复用的效果
      let loginRes = null;
      // 有 uuid 就是微信绑定手机号登录请求
      if (uuid) {
        console.log("微信绑定手机号登录");
        loginRes = await wechatBindingPhoneApi({
          phone: this.phoneNumber,
          verifyCode: this.messageCode,
          uuid,
        }); // 键和值相同，es6 可简写成一个
      } else {
        // 没有 uuid 就是普通登录请求
        loginRes = await phoneLoginApi({
          phone: this.phoneNumber,
          verifyCode: this.messageCode,
        });
      }
      // 有 uuid 的话，用完就删 uuid ，避免下次要普通登录还有 uuid，直接发微信绑定手机号请求；方法：短路运算
      uuid && localStorage.removeItem("uuid");
      // 响应状态嘛非零的话，就打断
      if (!loginRes) return;
      // alert("登录成功");
      this.asyncChangeIsShowToast({
        isShow: true,
        tMsg: "登录成功!",
        tType: "success",
      });
      // 把登录框状态复原
      this.phoneNumber = "";
      // 滑块验证码刷新复原
      /* this.onRefresh();
      this.msg = "向右滑动"; */ // 好像没有用
      this.messageCode = "";
      // 把响应的token存储起来
      localStorage.setItem("x-auth-token", loginRes["x-auth-token"]);
      // 登录按钮切换为购物车
      this.chanIsLogined(false);
      // 关闭登录模态框
      this.changeIsShowLoginModel(false);
      console.log({ loginRes });

      // 获取用户信息
      /* const getUserInfoRes = await getUserInfoApi();
      console.log({getUserInfoRes}); */
      this.asyncChangeUserInfo();
    },

    // 3、步骤三：点击展示二维码
    showQrCode() {
      this.isShowContent = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8081" + _this.$route.path)
        ),
        // 调用样式文件，引入转 base64 的 css
        href: "data:text/css;base64,Lyog57uE5Lu26YeM5YaZ5qC35byP5LiN55Sf5pWI77yM5omA5Lul6KaB5Y2V54us5Ye65p2l6L2s5oiQIGJhc2U2NCDnmoTlvaLlvI8gKi8NCi5pbXBvd2VyQm94IC50aXRsZSwNCi5pbXBvd2VyQm94IC5pbmZvIHsNCiAgICBkaXNwbGF5OiBub25lOw0KfQ0KDQovKiAuaW1wb3dlckJveCBxcmNvZGUgew0KICAgIG1hcmdpbi10b3A6IDIwcHg7DQp9ICov",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.loginModel {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    .close {
      /* width: 22px;
      height: 22px; */
      //   background: url("../assets/img/close.png");
      position: absolute;
      right: 56px;
      top: 12px;
    }
    .loginMethods {
      width: 254px;
      display: flex;
      margin: 50px auto 10px;
      height: 18px;
      li {
        margin: 0 15px;
        color: #bbb;
        cursor: pointer;
        // li{.class} 表示是 li 标签，的子元素类名，控制不了 li 的样式  只能控制 li 的子元素样式
        // li{ &.class} = li{class：value} 表示 li 标签的 串连选择器 样式都是作用在 li 标签上
        &.current {
          color: #000;
        }
      }
      span {
        border-right: 1px solid #ccc;
      }
    }
    .loginContent {
      width: 350px;
      margin: auto;
      padding-top: 20px;
      .cow {
        // width: 100%;
        display: flex;
        margin-bottom: 20px;
        input {
          height: 50px;
          flex: 1;
          text-indent: 1em;
          border: 1px solid #c9c9c9;
          outline: none;
          box-sizing: border-box;
        }
        button {
          height: 50px;
          border: none;
        }
        .btn {
          width: 84px;
          margin-left: 5px;
          background-color: #ddd;
        }

        .loginBtn {
          flex: 1;
          background-color: #0a328e;
          color: #fff;
          font-size: 18px;
        }
      }
    }
    .qrLogin {
      text-align: center;
    }
  }
}

// 滑块验证码样式
:deep(.slide-box) {
  // /deep/.slide-box {
  // 因为 style 设了 scoped 在此组件范围内可用 所以要设 /deep/，让样式在下载引入过来的组件也生效
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>